﻿/*
 * 原型模式
 */
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

namespace BF
{
    public interface IDeepCln
    {

    }

    /// <summary>
    /// 深复制接口
    /// 包含一个Clone()方法，由<see cref="PrototypeDeep"/>扩展实现
    /// </summary>
    public interface IDeepCln<T> : IDeepCln where T : class, IDeepCln
    {

    }

    /// <summary>
    /// 深复制
    /// </summary>
    public static class PrototypeDeep
    {
        /// <summary>
        /// 深复制
        /// </summary>
        public static T Cln<T>(this IDeepCln<T> iDeepClone) where T : class, IDeepCln
        {
            return DoDeepCln(iDeepClone) as T;
        }
        /// <summary>
        /// 深复制
        /// </summary>
        public static T DeepCln<T>(T t) where T : class
        {
            return DoDeepCln(t) as T;
        }

        /// <summary>
        /// 深复制
        /// </summary>
        private static object DoDeepCln(object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, obj);
                ms.Seek(0, SeekOrigin.Begin);

                return bf.Deserialize(ms);
            }
        }
    }
}